package com.aat.dizena.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

import com.aat.dxfy.utils.Atools;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**

 * @time 2016-05-25

 * @author 新歌<xingeking@163.com>

 * @email xingeking@163.com

 * @version v1.0

 * @function 加密解密

 * @info java mail

 * @update none

 */
@SuppressWarnings("restriction")
public class SecurityTools {

	/**

	 * DES加密

	 */
	public String jiami(String src) {
		try {
			// 初始化-- ENCRYPT_MODE：加密模式， key：密钥，iv：初始化向量


			c.init(Cipher.ENCRYPT_MODE, key, iv);
			byte[] srcByte = src.getBytes();
			// 加密


			byte[] targetByte = c.doFinal(srcByte);
			// Base64编码


			String targetString = new BASE64Encoder().encode(targetByte);
			return targetString;
		} catch (Exception e) {

		}
		return "";
	}

	/**

	 * DES解密

	 */
	public String jiemi(String srcString) {
		try {
			// 初始化-- DECRYPT_MODE：解密模式， key：密钥，iv：初始化向量


			c.init(Cipher.DECRYPT_MODE, key, iv);
			// Base64解码


			byte[] srcByte = new BASE64Decoder().decodeBuffer(srcString);
			// 解密


			byte[] targetByte = c.doFinal(srcByte);
			return new String(targetByte);
		} catch (Exception e) {

		}
		return "";
	}

	// 密钥生成器


	private KeyGenerator kg;

	// 对称密钥


	private SecretKey key;

	// 加解密时的初始化向量must be 8 bytes long


	private IvParameterSpec iv;

	// Cipher,加解密主体实例


	private Cipher c;

	// 该构造方法初始化DES密钥和Cipher


	public SecurityTools(String ss8){
		try{
			if(Atools.isNotEmpty(ss8)){
				ss8="abledxfy";
			}
			kg = KeyGenerator.getInstance("DES", "SunJCE");
			key = kg.generateKey();
			iv = new IvParameterSpec(ss8.getBytes("UTF-8"));
			c = Cipher.getInstance("DES/CBC/PKCS5Padding", "SunJCE");
		}catch(Exception e){
			
		}
	}

	public static void main(String[] args) {
		SecurityTools securityTools=new SecurityTools("12332199");
		String s1 = securityTools.jiami("123");
		System.out.println(s1);
		String s2=securityTools.jiemi(s1);
		System.out.println(s2);
	}
}